<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactFollow\Action\Sidebar;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\App\User\Contract\UserContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ContactFollow\Contract\ContactFollowTemplateContract;

/**
 * 客户画像 - 添加客户跟进模板.
 *
 * Class StoreTemplate
 * @Controller
 */
class TemplateStore extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var UserContract
     */
    protected $userContract;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Inject
     * @var ContactFollowTemplateContract
     */
    private $processTemplate;

    /**
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @RequestMapping(path="/sidebar/contactFollow/templateStore", methods="POST")
     */
    public function handle()
    {
        // 接收参数
        $params = [
            'name' => $this->request->input('name'),
            'contactId' => (int) $this->request->input('contactId'),
        ];
        // 校验重复
        if (! empty($this->processTemplate->getContactFollowTemplateByName(user()['corpId'], $params['name']))) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '模板名称重复，无法创建');
        }
        $tenant = $this->userContract->getUserById(user()['logUserId'], ['tenant_id']);
        # # 数据操作
        Db::beginTransaction();
        try {
            $data = [
                'name' => $params['name'],
                'corp_id' => user()['corpId'],
                'tenant_id' => $tenant['tenantId'] ?? 0,
                'create_user_id' => user()['id'],
                'contact_id' => $params['contactId'],
                'created_at' => date('Y-m-d H:i:s'),
            ];
            # # 添加模板
            $id = $this->processTemplate->createContactFollowTemplate($data);
            Db::commit();
            return [$id];
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '添加跟进模板失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'name' => 'required',
            'contactId' => 'required|integer|min:1|bail',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'name.required' => '跟进模板名称 必传',
            'contactId.required' => '客户id 必传',
        ];
    }
}
